package com.ycsj.goldmedalnewconcept.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.activity.UpdateSutdentInfoActivity;
import com.ycsj.goldmedalnewconcept.bean.PersonInfo;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;
import com.ycsj.goldmedalnewconcept.view.RoundImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 创建日期：2017/11/9  16:15
 * 描述:显示组员的GridView的适配器
 * 作者:张伟
 */

public class ClassGvAdapter extends CommonAdapter<PersonInfo> {
    private Activity activity;
    private Context context;
    private LinearLayout.LayoutParams lp;
    private List<PersonInfo> datas;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    //删除成功,业务有问题
                    PersonInfo personInfo = (PersonInfo) msg.obj;
                    personInfo.setName("");
                    personInfo.setIsdeleted(false);
                    notifyDataSetChanged();
                    break;
                case 200:
                    if (null != llLoading) {
                        llLoading.setVisibility(View.GONE);
                    }
                    if (null != llEmpty) {
                        llEmpty.setVisibility(View.VISIBLE);
                    }
                    if (null != lv) {
                        lv.setVisibility(View.GONE);
                    }
                    //网络请求失败
                    Toast.makeText(context, "网络错误", Toast.LENGTH_SHORT).show();
                    break;
                case 300:
                    //删除失败
                    Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show();
                    break;
                case 500:
                    //证明没有返回未分组的学生信息
                    if (null != lv) {
                        lv.setVisibility(View.GONE);
                    }
                    if (null != llEmpty) {
                        llEmpty.setVisibility(View.VISIBLE);
                    }
                    if (null != llLoading) {
                        llLoading.setVisibility(View.GONE);
                    }
                    break;
                case 800:
                    //解析数据异常
                    Toast.makeText(context, "数据异常", Toast.LENGTH_SHORT).show();
                    break;
                case 2000:
                    //收到添加未分组学生到小组的信息,主线程更新UI
                    //1.更新当前GridView的条目数据
//                    notifyDataSetChanged();
                    //2.更新展示未分组学生的列表数据
                    lvAdapter.notifyDataSetChanged();

                    //使用广播通知ClassInfoActivity界面进行刷新
                    Intent intent = new Intent();
                    intent.setAction("refreshbroadcast");
                    context.sendBroadcast(intent);

                    if (window != null && window.isShowing()) {
                        window.dismiss();
                    }
                    if (view != null) {
                        view = null;
                    }
                    break;
                case 3000:
                    //添加未分组学生到小组失败的信息
                    if (window != null && window.isShowing()) {
                        window.dismiss();
                    }
                    if (view != null) {
                        view = null;
                    }
                    Toast.makeText(context, "添加失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1000:
                    //请求服务器接口获取到未分组的学生信息
                    if (infos.size() == 0) {
                        //证明没有数据
                        if (null != lv) {
                            lv.setVisibility(View.GONE);
                        }
                        if (null != llEmpty) {
                            llEmpty.setVisibility(View.VISIBLE);
                        }
                        if (null != llLoading) {
                            llLoading.setVisibility(View.GONE);
                        }
                    } else {


                        if (null != lv) {
                            lv.setVisibility(View.VISIBLE);
                            if (null != llEmpty) {
                                llEmpty.setVisibility(View.GONE);
                            }
                            if (null != llLoading) {
                                llLoading.setVisibility(View.GONE);
                            }
                            //给展示未分组学生的ListView设置数据
                            lvAdapter = new StudentLvAdapter(context, infos, R.layout.item_lv_student);
                            lv.setAdapter(lvAdapter);
                            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                                    //未添加学生的条目点击事件
                                    //请求服务器将学生添加到指定位置
                                    // 调用将未分组的学生添加到组里的接口
                                    //请求服务器,删除该位置学生的信息
                                    OkHttpClient mOkHttpClient = new OkHttpClient();
                                    FormEncodingBuilder builder = new FormEncodingBuilder();
                                    builder.add("type", "12");
                                    builder.add("studentID", infos.get(i).getId() + "");//未分组学生的ID
                                    builder.add("studentTel", infos.get(i).getTel() + "");//未分组学生的电话
                                    builder.add("teamID", datas.get(clickpos).getTeamId());//需要添加学生位置的teamID
                                    builder.add("teamnum", datas.get(clickpos).getTeamnum() + "");//需要添加学生位置的teamNum
                                    builder.add("classnum", datas.get(clickpos).getClassnum() + "");//需要添加学生位置的classNum
                                    builder.add("role", role);

//                                Log.i("test", "上传给服务器的值是:teamID" + datas.get(clickpos).getTeamId());
//                                Log.i("test", "上传给服务器的值是:teamnum" +datas.get(clickpos).getTeamnum() + "");
//                                Log.i("test", "上传给服务器的值是:classnum" + datas.get(clickpos).getClassnum() + "");
//                                Log.i("test", "上传给服务器的值是:studentID" + infos.get(i).getId() + "");
//                                Log.i("test", "上传给服务器的值是:studentTel" + infos.get(i).getTel() + "");
//                                Log.i("test", "上传给服务器的值是:role" + role);

                                    Request request = new Request.Builder()
                                            .url(Constant.servlet_MessageController).post(builder.build())
//                                            .url("http://www.moregolden.com/ycsj_jpxgn/servlet/MessageController").post(builder.build())
                                            .build();
                                    mOkHttpClient.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
                                        @Override
                                        public void onFailure(Request request, IOException e) {
                                            Message message = new Message();
                                            message.what = 200;
                                            handler.sendMessage(message);
                                        }

                                        @Override
                                        public void onResponse(Response response) throws IOException {
                                            try {
                                                String json = response.body().string();
                                                JSONObject object = new JSONObject(json);
                                                String state = object.getString("state");
                                                if ("1".equals(state)) {
//                                                    datas.get(clickpos).setName(infos.get(i).getName());
//                                                    datas.get(clickpos).setIcon(infos.get(i).getIcon());
                                                    infos.remove(i);

                                                    Message message = new Message();
                                                    message.what = 2000;
                                                    handler.sendMessage(message);

                                                } else if ("-1".equals(state)) {
                                                    //添加失败
                                                    Message message = new Message();
                                                    message.what = 3000;
                                                    handler.sendMessage(message);
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                                Message message = new Message();
                                                message.what = 800;
                                                handler.sendMessage(message);
                                            }
                                        }
                                    });
                                }
                            });
                        }
                    }
                    break;
            }
        }
    };

    //显示未分组学生的数据集合
    private List<PersonInfo> infos;
    private View view;
    private PopupWindow window;
    //没有分组学生时需要展示的视图
    private LinearLayout llEmpty;
    //加载中显示的视图
    private LinearLayout llLoading;
    private ListView lv;
    private StudentLvAdapter lvAdapter;
    //定义上传给服务器的角色
    private String role;
    //点击的位置
    private int clickpos;


    public ClassGvAdapter(Context context, List<PersonInfo> datas, int layoutId, LinearLayout.LayoutParams lp, Activity activity) {
        super(context, datas, layoutId);
        this.context = context;
        this.lp = lp;
        this.datas = datas;
        this.activity = activity;
    }

    @Override
    public void convert(final ViewHolder holder, final PersonInfo personInfo) {
        //最外层布局
        LinearLayout llOut = holder.getView(R.id.ll_out);

        //条目的点击事件
        llOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(personInfo.getName())) {
                    //当前位置没有学生信息时点击才弹出侧面Pop
                    //根据选择的位置确定到组的位置信息
                    clickpos = holder.getPosition();
                    switch (clickpos) {
                        case 0:
                            role = "wisdom";
                            break;
                        case 1:
                            role = "brave";
                            break;
                        case 2:
                            role = "joy";
                            break;
                        case 3:
                            role = "love";
                            break;
                    }
                    showStudentPopWin(activity);
                } else {
//                    //当前位置有学生信息时不做任何操作
//                    UiHelper.toast(context, "该位置已经有学生了");
//                    return;
                	//当前位置有学生信息时,跳转到修改学生信息界面
                    Intent intent = new Intent(context, UpdateSutdentInfoActivity.class);
                    //携带学生信息过去
                    String json = GsonUtil.objectToJson(personInfo);
                    intent.putExtra("studentinfo", json);
                    context.startActivity(intent);

                }
            }
        });

        //学生头像
        RoundImageView lvPerson = holder.getView(R.id.lv_person);

        //删除图标
        ImageView lvDelete = holder.getView(R.id.lv_delete);
        if (personInfo.isdeleted()) {
            lvDelete.setVisibility(View.VISIBLE);
        } else {
            lvDelete.setVisibility(View.GONE);
        }

        //点击删除图标后的操作
        lvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //弹框提示删除
                new AlertDialog.Builder(context).setTitle("提示:")
                        .setMessage("确定删除该学生吗?")

                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                //请求服务器,删除该位置学生的信息
                                OkHttpClient mOkHttpClient = new OkHttpClient();
                                FormEncodingBuilder builder = new FormEncodingBuilder();
                                builder.add("type", "11");
                                //该学生的teadmID
                                builder.add("teamID", personInfo.getTeamId() + "");
                                builder.add("studentID", personInfo.getId() + "");
                                builder.add("studentTel", personInfo.getTel() + "");
                                Request request = new Request.Builder()
                                
                                .url(Constant.servlet_MessageController).post(builder.build())
//                                        .url("http://www.moregolden.com/ycsj_jpxgn/servlet/MessageController").post(builder.build())
                                        .build();
                                mOkHttpClient.newCall(request).enqueue(new Callback() {
                                    @Override
                                    public void onFailure(Request request, IOException e) {
                                        Message message = new Message();
                                        message.what = 200;
                                        handler.sendMessage(message);
                                    }

                                    @Override
                                    public void onResponse(Response response) throws IOException {
                                        String json = response.body().string();
                                        try {
                                            JSONObject jsonObject = new JSONObject(json);
                                            int state = jsonObject.getInt("state");
                                            if (state == 1) {
                                                //删除成功
                                                Message message = new Message();
                                                message.obj = personInfo;
                                                message.what = 100;
                                                handler.sendMessage(message);
                                            } else if (state == -1) {
                                                //删除失败
                                                Message message = new Message();
                                                message.what = 300;
                                                handler.sendMessage(message);
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            }
                        })
                        .setPositiveButton("取消", null)
                        .show();
            }
        });

        //学生姓名
        TextView tvName = holder.getView(R.id.tv_persnon_name);

        //获取当前条目的位置
        int pos = holder.getPosition();

        if (TextUtils.isEmpty(personInfo.getName())) {
            //使用本地图片和名称
            switch (pos) {
                case 0:
                    lvPerson.setImageResource(R.drawable.wisdom);
                    tvName.setText("智");
                    break;
                case 1:
                    lvPerson.setImageResource(R.drawable.brave);
                    tvName.setText("勇");
                    break;
                case 2:
                    lvPerson.setImageResource(R.drawable.enjoy);
                    tvName.setText("欢");
                    break;
                case 3:
                    lvPerson.setImageResource(R.drawable.love);
                    tvName.setText("爱");
                    break;
            }
        } else {
            //设置服务器返回的数据
            tvName.setText(personInfo.getName());
            //设置服务器返回的头像
            if (!personInfo.getIcon().endsWith(".jpg")) {
//                Picasso.with(context).load("http://m.moregolden.com/ycsj_jpxgn/img/" + personInfo.getIcon() + ".jpg").error(R.drawable.defaultimage).into(lvPerson);
                Picasso.with(context).load(Constant.SERVER_183+"ycsj_jpxgn/img/" + personInfo.getIcon() + ".jpg").error(R.drawable.defaultimage).into(lvPerson);
            } else {
                Picasso.with(context).load(Constant.SERVER_183+"ycsj_jpxgn/img/" + personInfo.getIcon()).error(R.drawable.defaultimage).into(lvPerson);
//                Picasso.with(context).load("http://m.moregolden.com/ycsj_jpxgn/img/" + personInfo.getIcon()).error(R.drawable.defaultimage).into(lvPerson);
            }
        }
    }


    /**
     * 屏幕右边弹出PopUpWindow的方法
     */
    private void showStudentPopWin(final Activity activity) {
        //请求服务器数据,获取是否有未分组的学生信息
        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormEncodingBuilder builder = new FormEncodingBuilder();
        builder.add("type", "10");
//        builder.add("userID", "13006314760");
        builder.add("userID", SPUtil.getString(context, "account", ""));
        Request request = new Request.Builder()
                .url(Constant.SERVER_183+"ycsj_count/KeJianMessage").post(builder.build())
//                .url("http://m.moregolden.com/ycsj_count/KeJianMessage").post(builder.build())
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Message message = new Message();
                message.what = 200;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    //获取服务器返回的json数据
                    final String json = response.body().string();
                    if (!TextUtils.isEmpty(json)) {
                        //证明返回的有未分组的学生信息
                        JSONObject stud = new JSONObject(json);

                        //创建显示未分组学生的集合
                        infos = new ArrayList<>();
                        for (int i = 0; i < stud.length() - 1; i++) {
                            JSONObject object = stud.getJSONObject("student" + i);
                            PersonInfo info = new PersonInfo();
                            info.setIcon(object.getString("icon"));
                            info.setBirthday(object.getString("birthday"));
                            info.setTeamnum(object.getInt("teamnum"));
                            info.setNickname(object.getString("nickname"));
                            info.setTel(object.getString("tel"));
                            info.setClassnum(object.getInt("classnum"));
                            info.setFavorite(object.getString("favorite"));
                            info.setId(object.getInt("id"));
                            info.setUserID(object.getString("userID"));
                            info.setExp(object.getInt("exp"));
                            info.setSchool(object.getString("school"));
                            info.setAddress(object.getString("address"));
                            info.setName(object.getString("name"));
                            info.setMoney(object.getInt("money"));
                            info.setGender(object.getString("gender"));
                            info.setGrade(object.getString("grade"));
                            info.setPayment(object.getString("payment"));
                            infos.add(info);
                        }
                        //使用Handler发送消息 去更新UI界面
                        Message message = new Message();
                        message.what = 1000;
                        handler.sendMessage(message);

                    } else {
                        //证明返回的没有学生信息
                        Message message = new Message();
                        message.what = 500;
                        handler.sendMessage(message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = 800;
                    handler.sendMessage(message);
                }
            }
        });

        view = View.inflate(context, R.layout.pop_student, null);
        //加载视图
        llLoading = (LinearLayout) view.findViewById(R.id.ll_loading);
        llEmpty = (LinearLayout) view.findViewById(R.id.ll_empty);
        //展示学生列表的数据
        lv = (ListView) view.findViewById(R.id.lv);
        window = new PopupWindow(view, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.MATCH_PARENT);
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        backgroundAlpha(activity, 0.8f);
        window.setAnimationStyle(R.style.AnimationRightFade);
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(activity, 1.0f);
            }
        });
        window.showAtLocation(activity.getLayoutInflater().inflate(R.layout.activity_class_info, null), Gravity.RIGHT, 0, 0);
    }


    /**
     * 改变屏幕透明度 方法
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        activity.getWindow().setAttributes(lp);
    }

}
